import router from './router/index'
import store from './store/modules'
import { getToken } from '@/utils/auth'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({ showSpinner: false })

const whiteList = ['/', '/login', '/register', '/forgot-password']
let isAddRoutesComplete = false // 添加标识

// 添加路由并返回是否需要重定向
async function addDynamicRoutes() {
  if (isAddRoutesComplete) return false
  
  try {
    // 生成路由
    const accessRoutes = await store.dispatch('permission/generateRoutes')
    
    // 添加路由
    accessRoutes.forEach((route: any) => {
      if (!router.hasRoute(route.name)) {
        router.addRoute(route)
      }
    })
    
    // 添加404路由
    if (!router.hasRoute('NotFound')) {
      router.addRoute({
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: () => import('@/views/error/404.vue')
      })
    }
    
    isAddRoutesComplete = true
    return true
  } catch (error) {
    console.error('添加路由失败:', error)
    return false
  }
}

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  
  const hasToken = getToken()
  
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/dashboard' })
    } else {
      try {
        // 获取用户信息
        const hasRoles = store.state.user.roles && store.state.user.roles.length > 0
        if (!hasRoles) {
          await store.dispatch('user/getInfo')
        }
        
        // 判断路由是否需要重新加载
        if (!isAddRoutesComplete || to.matched.length === 0) {
          const needRedirect = await addDynamicRoutes()
          
          if (needRedirect) {
            // 重要：重新获取匹配的路由
            const newTo = router.resolve(to.fullPath)
            if (newTo.matched.length > 0) {
              next({ ...to, replace: true })
              return
            }
          }
        }
        
        // 确保路由存在
        if (to.matched.length === 0) {
          // 如果路由不存在，先尝试重新加载路由
          const needRedirect = await addDynamicRoutes()
          if (needRedirect) {
            const newTo = router.resolve(to.fullPath)
            if (newTo.matched.length > 0) {
              next({ ...to, replace: true })
              return
            }
          }
          // 如果还是不存在，才跳转到404
          next('/404')
          return
        }
        
        // 根据角色控制路由访问
        const userRole = store.state.user.role
        if (to.path === '/counseling/create' && userRole !== 'student') {
          next('/403')
          return
        }
        
        if (to.path === '/counseling/manage' && !['admin', 'counselor'].includes(userRole)) {
          next('/403')
          return
        }
        
        next()
      } catch (error) {
        console.error('路由守卫错误:', error)
        isAddRoutesComplete = false
        await store.dispatch('user/resetToken')
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  } else {
    isAddRoutesComplete = false
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

// 重置路由方法
export function resetRouter() {
  isAddRoutesComplete = false
  // 清除所有动态添加的路由
  router.getRoutes().forEach(route => {
    if (route.name && !['Login', 'NotFound'].includes(route.name as string)) {
      router.removeRoute(route.name)
    }
  })
}